package org.bambrikii.dictionary.managers;

import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.bambrikii.dictionary.Article;
import org.bambrikii.dictionary.Word;
import org.bambrikii.dictionary.WordContext;
import org.bambrikii.dictionary.dao.IArticleDAO;
import org.bambrikii.dictionary.dao.IWordContextDAO;
import org.bambrikii.dictionary.dao.IWordDAO;
import org.bambrikii.site.base.business.managers.ManagerBase;
import org.bambrikii.site.base.business.managers.core.ManagerException;
import org.bambrikii.site.base.model.Pager;

public class DictionaryManager extends ManagerBase<Article, IArticleDAO> {

	private IWordContextDAO ctxDao = null;
	private IWordDAO wrdDao = null;

	public DictionaryManager(IArticleDAO dao, IWordContextDAO ctxDao,
			IWordDAO wrdDao) throws ManagerException {
		super(dao);
		this.ctxDao = ctxDao;
		this.wrdDao = wrdDao;
	}

	@Override
	public void saveOrUpdate(final Article article) {
		if (article.getId() == null) {
			article.setInsertionTime(Calendar.getInstance().getTime());
		}
		dao.saveOrUpdate(article);
	}

	public void saveWords(final List<String> words) {
		for (final String word : words) {
			Word w = wrdDao.find(word);
			if (w == null) {
				w = new Word();
				w.setValue(word);
				wrdDao.saveOrUpdate(w);
			}
		}
	}

	public Word saveWord(final String word) {
		Word w = wrdDao.find(word);
		if (w == null) {
			w = new Word();
			w.setValue(word);
			wrdDao.saveOrUpdate(w);
		}
		return w;
	}

	public WordContext setWordContext(final Article article, final Word word,
			final String meaning) {
		WordContext ctx = ctxDao.find(article, word);
		if (ctx == null) {
			ctx = new WordContext();
			ctx.setArticle(article);
			ctx.setWord(word);
		}
		ctx.setMeaning(meaning);
		ctxDao.saveOrUpdate(ctx);
		return ctx;
	}

	public Pager<Article> getArticlesPager(final String title,
			final String order, final int currPage) {
		final Pager<Article> pager = new Pager<Article>(1, 150);
		pager.setCurrPage(currPage);
		pager.setTotalRecordsCount(dao.getCount(title));
		pager.setRecords(dao.getList("%" + title + "%", order,
				pager.getStart(), pager.getLength()));
		return pager;
	}

	public Map<String, Map<Integer, String>> getContexts(final Article article,
			final List<String> words) {
		return ctxDao.getContexts(article, words);
	}
}
